package com.snack.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snack.common.result.Result;
import com.snack.entity.dto.LoginDTO;
import com.snack.entity.dto.UserDTO;
import com.snack.entity.pojo.Store;
import com.snack.entity.pojo.User;
import com.snack.mapper.UserMapper;
import com.snack.service.LoginService;
import com.snack.service.StoreService;
import com.snack.utils.PasswordUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.net.http.HttpRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.snack.utils.RedisConstants.*;


/**
 * @author huangfuhao
 * @Date 2025/3/13
 */
@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private StoreService storeService;

    @Override
    public Result login(User user) {
        log.info("用户登录接口");

        String username = user.getUsername();
        String password = user.getPassword();

        //1.查找用户是否存在
        User one = lambdaQuery().eq(User::getUsername, username).one();
        if (one == null) {
            return Result.error("用户不存在");
        }

        //2.存在，判断密码是否正确
        String password1 = one.getPassword();

        if (!PasswordUtil.encodePassword(password).equals(password1)) {
            return Result.error("用户名或密码错误");
        }

        //3.保存用户信息到redis
        //3.1随机生成token，作为登录令牌
        String token = UUID.randomUUID().toString(true);


        //  3.3存储
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForValue().set(tokenKey, one.getId() + "");
        //  3.4设置token有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        //查询用户所在店铺的店铺名称
        Store store = new Store();
        if (one.getStoreId() != null) {
            store = storeService.lambdaQuery().eq(Store::getId, one.getStoreId()).one();
        }

        LoginDTO loginDTO = LoginDTO.builder()
                .id(one.getId())
                .username(one.getUsername())
                .roleId(one.getRoleId())
                .storeId(one.getStoreId())
                .storeName(store.getName())
                .token(token).build();
        return Result.success(loginDTO);

    }

    @Override
public Result logout(HttpServletRequest request) {
    log.info("用户退出登录接口");

    // 从请求头中获取用户的登录令牌
    String token = request.getHeader("Authorization");
    if (token == null) {
        return Result.error("未找到有效的登录令牌");
    }

    // 构建 Redis 中的键
    String tokenKey = LOGIN_USER_KEY + token;

    // 删除 Redis 中的令牌
    Boolean deleted = stringRedisTemplate.delete(tokenKey);
    if (deleted != null && deleted) {
        return Result.success("退出登录成功");
    } else {
        return Result.error("退出登录失败");
    }
}

}
